<?php

namespace app\api\service;

use app\api\model\BaseModel;
use app\api\model\Product;
use app\lib\exception\OrderException;
use think\Cache;
use think\Exception;

class Order extends BaseModel
{

    protected $orderProducts;
    protected $uid;
    protected $products;

    
    public function place($uid, $orderProducts)
    {
        $this->uid = $uid;
        $this->orderProducts = $orderProducts;
        
        $this->products = $this->getProductsByOrder($orderProducts);
    }

    /**
     * 获取订单状态
     * @return array
     * @throws OrderException
     */
    public function getOrderStatus()
    {
       $orderStatus = [
           'pass'               => true,            //订单信息是否有效
           'orderPrice'         => 0,               //订单总金额
           'productStatusArray' => []               //订单中的单个商品信息
       ];

        foreach ($this->orderProducts as $oProduct) {
            $pStatus = $this->getProductStatus(
                $oProduct['product_id'], $oProduct['count'], $this->products
            );

            if ( !$pStatus['haveStock']) $orderStatus['pass'] = false;
            $orderStatus['orderPrice'] += $pStatus['totalPrice'];
            array_push($orderStatus['productStatusArray'], $pStatus);
        }

        return $orderStatus;
    }

    /**
     * 获取订单中单个商品的状态
     * @param $oProductID
     * @param $oCount
     * @param $products
     * @return array
     * @throws OrderException
     */
    protected function getProductStatus($oProductID, $oCount, $products)
    {
        $pIndex  = -1;
        $pStatus = [
            'id'            => null,
            'haveStock'     => false,
            'count'         => 0,
            'name'          => '',
            'totalPrice'    => 0,
        ];
        
        for($i = 0; $i < count($products); $i++) {
            if ( $oProductID == $products['id']) {
                $pIndex = $i;
                break;
            }
        }
        
        if ( -1 == $pIndex) {
            throw new OrderException();
        }

        $productInfo           = $products[$pIndex];
        $pStatus['id']         = $productInfo['id'];
        $pStatus['name']       = $productInfo['name'];
        $pStatus['count']      = $oCount;
        $pStatus['totalPrice'] = $oCount * $productInfo['price'];
        $pStatus['haveStock']  = boolval($productInfo['stock'] > $oCount);

        return $pStatus;
    }

    /**
     * 获取数据库中的商品库存信息
     * @param $orderProducts
     * @return mixed
     */
    protected function getProductsByOrder($orderProducts)
    {
        $productIDs = array_column($orderProducts, 'product_id');

        $products = Product::all($productIDs)->visible(['id', 'price', 'stock', 'name', 'main_img_url'])
                    ->toArray();

        return $products;
    }
}